package com.leff.cards.ui;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.ActionBar.Tab;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.google.android.gcm.GCMRegistrar;
import com.leff.cards.R;
import com.leff.cards.data.AppState;
import com.leff.cards.ui.fragment.GroupsFragment;
import com.leff.cards.ui.fragment.InvitationsFragment;
import com.leff.cards.ui.fragment.SettingsFragment;
import com.leff.cards.ui.util.FragmentTabListener;
import com.leff.cards.util.Secrets;
import com.leff.cards.util.FacebookSession;
import com.leff.cards.util.Settings;
import com.leff.cards.web.QueryDispatcher;
import com.leff.cards.web.requests.GcmRegisterRequest;
import com.leff.cards.web.requests.GcmUnregisterRequest;
import com.leff.cards.web.requests.LoginRequest;
import com.leff.notifications.NotificationCenter;
import com.leff.notifications.NotificationListener;

public class HomeActivity extends BaseActivity implements Secrets, NotificationListener {
	
	public static final String ACTION_LOGOUT = "com.leff.cards.ACTION_LOGOUT";
	
	private static final String SELECTED_TAB_KEY = "selected_tab";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		ActionBar actionBar = this.getSupportActionBar();
		
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
	    actionBar.setDisplayShowTitleEnabled(true);
		
	    actionBar.addTab(
				actionBar.newTab()
				.setText(R.string.groups)
				.setTabListener(new FragmentTabListener<GroupsFragment>(this, "groups", GroupsFragment.class))
				);
	    
	    actionBar.addTab(
				actionBar.newTab()
				.setText(R.string.invites)
				.setTabListener(new FragmentTabListener<InvitationsFragment>(this, "invites", InvitationsFragment.class))
				);
	    
	    actionBar.addTab(
				actionBar.newTab()
				.setText(R.string.settings)
				.setTabListener(new FragmentTabListener<SettingsFragment>(this, "settings", SettingsFragment.class))
				);
	    
	    if(savedInstanceState != null) {
	    	int tab = savedInstanceState.getInt(SELECTED_TAB_KEY, 0);
	    	actionBar.setSelectedNavigationItem(tab);
	    	
	    	return;
	    }
	    
	    Intent I = this.getIntent();
	    Bundle extras = I.getExtras();
	    if(extras != null) {
	    	boolean login = extras.getBoolean("doLogin", false);
	    	if(login) {
	    		AppState.get().beginLogin();
	    	}
	    }
	}
	
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		
		int tab = this.getSupportActionBar().getSelectedNavigationIndex();
		outState.putInt(SELECTED_TAB_KEY, tab);
	}

	@Override
	protected void onResume() {
		super.onResume();

		NotificationCenter.registerListener(this, AppState.APP_STATE_INITIALIZED);
		NotificationCenter.registerListener(this, LoginRequest.LOGGED_IN);
		NotificationCenter.registerListener(this, FacebookSession.FB_LOGIN_FAILED);
		NotificationCenter.registerListener(this, AppState.INVITES_REFRESHED);
	}

	@Override
	protected void onPause() {
		super.onPause();

		NotificationCenter.unregisterListener(this, AppState.APP_STATE_INITIALIZED);
		NotificationCenter.unregisterListener(this, LoginRequest.LOGGED_IN);
		NotificationCenter.unregisterListener(this, FacebookSession.FB_LOGIN_FAILED);
		NotificationCenter.unregisterListener(this, AppState.INVITES_REFRESHED);
	}

	private void doGcmRegistration() {
		GCMRegistrar.checkDevice(this);

		String regId = GCMRegistrar.getRegistrationId(this);
		if(regId == null || regId.equals("")) {
			Log.v(TAG, "Registering with GCM");
			GCMRegistrar.register(this, GCM_SENDER_ID);
		} else {
			Log.v(TAG, "Already registered with GCM");
			
			long id = AppState.get().getUser().id;
			new QueryDispatcher(new GcmRegisterRequest(id, regId)).execute();
		}
	}

	@Override
	public void onNotificationPosted(String action, Object data, Object sender) {
		super.onNotificationPosted(action, data, sender);
		
		if(action.equals(LoginRequest.LOGGED_IN)) {
			if(Settings.getNotificationsEnabled()) {
				doGcmRegistration();
			}
			if(Settings.needsUpgrade()) {
				showUpgradeDialog();
			}
		}
		else if(action.equals(FacebookSession.FB_LOGIN_FAILED)) {
			
			Toast.makeText(this, (String)data, Toast.LENGTH_LONG).show();
			
			Intent I = new Intent(this, LoginActivity.class);
			startActivity(I);
			
			finish();
		}
		else if(action.equals(AppState.INVITES_REFRESHED)) {
			
			int count = AppState.get().getInvites().size();
			Tab tab = getSupportActionBar().getTabAt(1);
			if(count == 0) {
				tab.setText(R.string.invites);
			} else {
				String text = String.format(getResources().getString(R.string.invites_count), count);
				tab.setText(text);
			}
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		MenuInflater MI = this.getSupportMenuInflater();
		MI.inflate(R.menu.home_menu, menu);
		
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if(item.getItemId() == R.id.menu_logout) {
			FacebookSession.getSession().logout(this);
			
			String regId = GCMRegistrar.getRegistrationId(this);
			if(regId == null || regId.equals("")) {
				Log.v(TAG, "No device registered, not sending unregister request with log out.");
			} else {
				Log.v(TAG, "Unregistering device with GCM because of log out.");
				
				long id = AppState.get().getUser().id;
				new QueryDispatcher(new GcmUnregisterRequest(id, regId, true)).execute();
			}
			
			this.finish();
			
			Intent I = new Intent(this, LoginActivity.class);
			I.setAction(ACTION_LOGOUT);
			startActivity(I);
			
			return true;
		}
		else if(item.getItemId() == R.id.menu_refresh) {
			
			AppState.get().beginLogin();
		}
		return super.onOptionsItemSelected(item);
	}
	
	public void showUpgradeDialog() {
		
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		
		builder.setTitle(R.string.update_title);
		builder.setMessage(R.string.update_message);
		
		builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {

				String url = APK_URL;
				Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
				startActivity(browserIntent);
				finish();
			}
		});
		builder.setNegativeButton(R.string.no_thanks, null);
		
		builder.create().show();
	}
}
